﻿<template>
  <s-layout
    title="商品分类"
    tabbar="/pages/index/category"
    :bgStyle="{ color: '#f5f7fa' }"
  >
    <view class="page-container">
      <view
        class="store-header"
        :style="{ paddingTop: statusBarHeight + 44 + 'px' }"
      >
        <view class="store-card" @tap="showStoreModal">
          <view class="store-left">
            <view class="location-icon">
              <uni-icons type="location" size="18" color="#ffffff"></uni-icons>
            </view>
            <view class="store-content">
              <view class="store-label">当前门店</view>
              <view class="store-name">{{
                (state.selectedStore && state.selectedStore.name) ||
                "请选择门店"
              }}</view>
            </view>
          </view>
          <view class="store-right">
            <text
              class="distance"
              v-if="state.selectedStore && state.selectedStore.distance"
            >
              {{ formatDistance(state.selectedStore.distance) }}
            </text>
          </view>
        </view>
      </view>

      <view
        class="category-container"
        :style="{ paddingTop: statusBarHeight + 40 + 'px' }"
      >
        <view class="main-content">
          <view class="sidebar">
            <scroll-view class="menu-scroll" scroll-y>
              <view class="menu-wrapper">
                <view
                  class="menu-item"
                  v-for="(item, index) in state.categoryList"
                  :key="item.id"
                  :class="{ active: index === state.activeMenu }"
                  @tap="onMenu(index)"
                >
                  <view class="menu-indicator"></view>
                  <text class="menu-text">{{ item.name }}</text>
                </view>
              </view>
            </scroll-view>
          </view>

          <scroll-view
            class="content-area"
            scroll-y
            v-if="state.categoryList && state.categoryList.length"
            @scrolltolower="loadmore"
            :lower-threshold="150"
          >
            <view class="category-header">
              <view
                class="category-banner"
                v-if="state.selectedCategory && state.selectedCategory.icon"
              >
                <image
                  class="banner-image"
                  :src="sheep.$url.cdn(state.selectedCategory.icon)"
                  mode="aspectFill"
                />
                <view class="banner-overlay">
                  <view class="banner-info">
                    <text class="banner-title">{{
                      state.selectedCategory.name
                    }}</text>
                    <text class="banner-desc">发现更多精选商品</text>
                  </view>
                </view>
              </view>

             
            </view>

            <view class="goods-section">
              <view
                v-if="state.loading && !state.goodsList.length"
                class="skeleton-wrapper"
              >
                <view class="skeleton-item" v-for="i in 6" :key="i">
                  <view class="skeleton-image"></view>
                  <view class="skeleton-text"></view>
                  <view class="skeleton-price"></view>
                </view>
              </view>

              <view
                v-if="state.goodsList.length"
                :class="['goods-' + state.viewMode]"
              >
                <view
                  class="goods-card"
                  v-for="item in state.goodsList"
                  :key="item.id"
                  @tap="navigateToGoods(item)"
                >
                  <view class="card-inner">
                    <view class="image-wrapper">
                      <image
                        class="goods-image"
                        :src="item.pic"
                        mode="aspectFill"
                        lazy-load
                      />
                      <view class="promotion-tag" v-if="item.promotionType">
                        {{ getPromotionText(item.promotionType) }}
                      </view>
                    </view>
                    <view class="goods-info">
                      <text class="goods-title">{{ item.name }}</text>
                      <view class="price-section">
                        <view class="price-main">
                          <text class="price-symbol">¥</text>
                          <text class="price-value">{{
                            formatPrice(isVipUser ? item.price2 : item.price)
                          }}</text>
                        </view>
                        <text
                          class="price-original"
                          v-if="isVipUser || item.marketPrice > item.price"
                        >
                          ¥{{
                            formatPrice(
                              isVipUser ? item.price : item.marketPrice
                            )
                          }}
                        </text>
                      </view>
                    </view>
                  </view>
                </view>
              </view>

              <view class="load-more-wrapper" v-if="state.goodsList.length">
                <uni-load-more
                  :status="state.loadStatus"
                  :content-text="{
                    contentdown: '上拉加载更多',
                    contentrefresh: '正在加载...',
                    contentnomore: '没有更多了',
                  }"
                  @tap="loadmore"
                />
              </view>

              <view
                class="empty-wrapper"
                v-if="!state.goodsList.length && !state.loading"
              >
                <s-empty icon="/static/empty-goods.png" text="该分类暂无商品" />
              </view>
            </view>
          </scroll-view>
        </view>
      </view>
    </view>

    <uni-popup
      ref="storeModal"
      type="bottom"
      :maskClick="true"
      @close="closeStoreModal"
    >
      <view class="store-popup">
        <view class="popup-header">
          <text class="popup-title">选择门店</text>
          <view class="close-btn" @tap="closeStoreModal">
            <uni-icons type="close" size="14" color="#666666"></uni-icons>
          </view>
        </view>

        <scroll-view class="store-list" scroll-y>
          <view
            class="store-item"
            v-for="store in state.storeList"
            :key="store.id"
            :class="{ active: state.selectedStore?.id === store.id }"
            @tap="selectStore(store)"
          >
            <view class="store-item-icon">
              <uni-icons type="shop" size="14" color="#667eea"></uni-icons>
            </view>
            <view class="store-item-content">
              <text class="store-item-name">{{ store.name }}</text>
              <text class="store-item-address">{{ store.address }}</text>
            </view>
            <view class="store-item-extra">
              <text class="store-item-distance">{{
                formatDistance(store.distance)
              }}</text>
              <view
                class="check-icon"
                v-if="state.selectedStore?.id === store.id"
              >
                <uni-icons type="checkmarkempty" size="10" color="#ffffff"></uni-icons>
              </view>
            </view>
          </view>

          <view
            class="empty-state"
            v-if="!state.storeList.length && !state.storeLoading"
          >
            <uni-icons type="info" size="40" color="#ddd"></uni-icons>
            <text class="empty-text">暂无附近门店</text>
          </view>

          <view class="loading-state" v-if="state.storeLoading">
            <text class="loading-text">正在获取门店信息...</text>
          </view>
        </scroll-view>
      </view>
    </uni-popup>
  </s-layout>
</template>

<script setup>
import sheep from "@/sheep";
import request from "@/sheep/request";
import { onLoad, onReachBottom } from "@dcloudio/uni-app";
import { computed, reactive, ref } from "vue";
import _ from "lodash";

const storeModal = ref(null);

const state = reactive({
  categoryList: [],
  activeMenu: 0,
  selectedCategory: null,
  goodsList: [],
  pagination: {
    data: [],
    current_page: 1,
    total: 0,
    last_page: 1,
    size: 10,
  },
  loadStatus: "",
  loading: false,
  storeList: [],
  selectedStore: null,
  storeLoading: false,
  viewMode: "grid",
  sortType: "default",
  sortAsc: true,
});

const { safeArea, safeAreaInsets } = sheep.$platform.device;

const statusBarHeight = computed(() => {
  return safeAreaInsets.top || uni.getSystemInfoSync().statusBarHeight || 44;
});

const isVipUser = computed(() => {
  try {
    const userStore = uni.getStorageSync("user-store");
    if (userStore && typeof userStore === "object") {
      return userStore.userInfo && userStore.userInfo.level > 0;
    }
    if (userStore && typeof userStore === "string") {
      const parsed = JSON.parse(userStore);
      return parsed.userInfo && parsed.userInfo.level > 0;
    }
  } catch (error) {
    return false;
  }
  return false;
});

async function getCategoryList() {
  try {
    const res = await sheep.$api.category.list();
    if (res && Array.isArray(res)) {
      state.categoryList = res.sort((a, b) => (a.sort || 0) - (b.sort || 0));
      if (state.categoryList.length > 0) {
        state.selectedCategory = state.categoryList[0];
        getGoodsList(state.selectedCategory.id);
      }
    }
  } catch (error) {
    uni.showToast({
      title: "获取分类失败",
      icon: "none",
    });
  }
}

const onMenu = (index) => {
  if (state.activeMenu === index) return;

  state.activeMenu = index;
  state.selectedCategory = state.categoryList[index];
  state.goodsList = [];
  state.pagination = {
    data: [],
    current_page: 1,
    total: 0,
    last_page: 1,
    size: 10,
  };

  getGoodsList(state.selectedCategory.id);
};

async function getGoodsList(categoryId, isLoadMore = false) {
  if (!categoryId || state.loading) return;

  state.loading = true;
  state.loadStatus = "loading";

  try {
    const params = {
      categoryId,
      orderField:
        state.sortType === "price"
          ? "price"
          : state.sortType === "sales"
          ? "salesCount"
          : "sort",
      orderSort: state.sortAsc ? "asc" : "desc",
    };

    const res = await sheep.$api.goods.list(params, {
      page: state.pagination.current_page - 1,
      size: state.pagination.size,
    });

    if (res) {
      const { content = [], totalElements = 0, totalPages = 0 } = res;

      if (isLoadMore) {
        state.goodsList = _.concat(state.goodsList, content);
      } else {
        state.goodsList = content;
      }

      state.pagination.total = totalElements;

      if (state.pagination.current_page < totalPages) {
        state.loadStatus = "more";
      } else {
        state.loadStatus = "noMore";
      }
    }
  } catch (error) {
    state.loadStatus = "error";
    uni.showToast({
      title: "加载失败",
      icon: "none",
    });
  } finally {
    state.loading = false;
  }
}

function loadmore() {
  if (state.loadStatus === "more" && !state.loading) {
    state.pagination.current_page++;
    getGoodsList(state.selectedCategory?.id, true);
  }
}

async function getNearbyStores() {
  state.storeLoading = true;
  try {
    uni.getLocation({
      type: "gcj02",
      success: async (res) => {
        const { latitude, longitude } = res;
        const storeData = {
          latitude: latitude.toString(),
          longitude: longitude.toString(),
        };

        try {
          let stores;
          if (sheep.$api.store && sheep.$api.store.getNearbyStores) {
            stores = await sheep.$api.store.getNearbyStores(storeData);
          } else {
            stores = await request({
              url: "/no-auth/stores/nearby",
              method: "POST",
              data: storeData,
              custom: {
                showLoading: false,
                showError: true,
              },
            });
          }

          if (stores && Array.isArray(stores)) {
            state.storeList = stores;

            const storedStoreId = uni.getStorageSync("selectedStoreId");
            if (storedStoreId) {
              const storedStore = stores.find(
                (store) => store.id === storedStoreId
              );
              if (storedStore) {
                state.selectedStore = storedStore;
              } else if (stores.length > 0) {
                state.selectedStore = stores[0];
                uni.setStorageSync("selectedStoreId", stores[0].id);
              }
            } else if (stores.length > 0) {
              state.selectedStore = stores[0];
              uni.setStorageSync("selectedStoreId", stores[0].id);
            }
          }
        } catch (apiError) {
          uni.showToast({
            title: "获取门店列表失败",
            icon: "none",
          });
        }
      },
      fail: (err) => {
        uni.showModal({
          title: "温馨提示",
          content: "需要获取您的位置信息来显示附近门店",
          confirmText: "去设置",
          success: (res) => {
            if (res.confirm) {
              uni.openSetting();
            }
          },
        });
      },
      complete: () => {
        state.storeLoading = false;
      },
    });
  } catch (error) {
    state.storeLoading = false;
  }
}

function showStoreModal() {
  if (state.storeList.length === 0) {
    getNearbyStores();
  }
  storeModal.value?.open();
}

function closeStoreModal() {
  storeModal.value?.close();
}

function selectStore(store) {
  state.selectedStore = store;
  uni.setStorageSync("selectedStoreId", store.id);
  closeStoreModal();
  uni.showToast({
    title: `已切换门店`,
    icon: "success",
  });
}

function formatDistance(distance) {
  if (!distance) return "";
  if (distance < 1) {
    return `${Math.round(distance * 1000)}m`;
  } else {
    return `${distance.toFixed(1)}km`;
  }
}

function formatPrice(price) {
  return price.toFixed(2);
}

function getPromotionText(type) {
  const map = {
    discount: "限时折扣",
    groupon: "拼团",
    seckill: "秒杀",
    bargain: "砍价",
  };
  return map[type] || "活动";
}

function navigateToGoods(item) {
  sheep.$router.go("/pages/goods/index", { id: item.id });
}

function toggleView() {
  state.viewMode = state.viewMode === "grid" ? "list" : "grid";
}

function toggleSort() {
  const sorts = ["default", "price", "sales"];
  const currentIndex = sorts.indexOf(state.sortType);
  if (currentIndex === sorts.length - 1) {
    state.sortType = sorts[0];
    state.sortAsc = true;
  } else {
    state.sortType = sorts[currentIndex + 1];
    if (state.sortType === sorts[currentIndex + 1] && !state.sortAsc) {
      state.sortAsc = true;
    } else if (state.sortType === sorts[currentIndex]) {
      state.sortAsc = !state.sortAsc;
    }
  }
  refreshData();
}

function getSortText() {
  const map = {
    default: "默认排序",
    price: "价格",
    sales: "销量",
  };
  return map[state.sortType];
}

function refreshData() {
  state.goodsList = [];
  state.pagination.current_page = 1;
  getGoodsList(state.selectedCategory?.id);
}

onLoad(async (options) => {
  await getCategoryList();
  await getNearbyStores();
});

onReachBottom(() => {
  loadmore();
});
</script>

<style lang="scss" scoped>

.page-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background: #f5f7fa;
}

.store-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  background: #ffffff;
  padding: 0 24rpx 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);

  .store-card {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: linear-gradient(135deg, #f8f9ff 0%, #f3f5ff 100%);
    border-radius: 20rpx;
    padding: 24rpx;
    margin-top: 16rpx;
    box-shadow: 0 2rpx 12rpx rgba(102, 126, 234, 0.08);

    .store-left {
      display: flex;
      align-items: center;
      flex: 1;

      .location-icon {
        width: 72rpx;
        height: 72rpx;
        background: #667eea;
        border-radius: 16rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 20rpx;

        .iconfont {
          font-size: 36rpx;
          color: #ffffff;
        }
      }

      .store-content {
        flex: 1;

        .store-label {
          font-size: 24rpx;
          color: #8892b0;
          margin-bottom: 4rpx;
        }

        .store-name {
          font-size: 30rpx;
          font-weight: 600;
          color: #2d3561;
          line-height: 1.3;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }

    .store-right {
      display: flex;
      align-items: center;
      gap: 12rpx;

      .distance {
        font-size: 26rpx;
        color: #667eea;
        font-weight: 500;
      }

      .iconfont {
        font-size: 24rpx;
        color: #8892b0;
      }
    }
  }
}

.category-container {
  background: #f5f7fa;
  overflow: hidden;
  height: calc(100vh - 160rpx);

  .main-content {
    display: flex;
    background: #ffffff;
    height: 100%;

    .sidebar {
      width: 180rpx;
      background: #f8f9fa;
      height: 100%;
      flex-shrink: 0;

      .menu-scroll {
        height: 100%;

        

        .menu-item {
          display: flex;
          align-items: center;
          padding: 28rpx 24rpx;
          position: relative;
          transition: all 0.3s ease;

          .menu-indicator {
            width: 4rpx;
            height: 0;
            background: #667eea;
            position: absolute;
            left: 0;
            border-radius: 0 2rpx 2rpx 0;
            transition: height 0.3s ease;
          }

          .menu-text {
            font-size: 28rpx;
            color: #666666;
            font-weight: 400;
            transition: all 0.3s ease;
            margin-left: 8rpx;
          }

          &.active {
            background: #ffffff;

            .menu-indicator {
              height: 32rpx;
            }

            .menu-text {
              color: #667eea;
              font-weight: 600;
            }
          }
        }
      }
    }

    .content-area {
      flex: 1;
      background: #f5f7fa;
      height: 100%;

      .category-header {
        background: #ffffff;
        position: sticky;
        top: 0;
        z-index: 10;

        .category-banner {
          position: relative;
          height: 320rpx;
          overflow: hidden;

          .banner-image {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }

          .banner-overlay {
            position: absolute;
            inset: 0;
            background: linear-gradient(
              180deg,
              transparent 0%,
              rgba(0, 0, 0, 0.4) 100%
            );
            display: flex;
            align-items: flex-end;
            padding: 32rpx;

            .banner-info {
              .banner-title {
                display: block;
                color: #ffffff;
                font-size: 36rpx;
                font-weight: 700;
                margin-bottom: 8rpx;
                text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.3);
              }

              .banner-desc {
                display: block;
                color: rgba(255, 255, 255, 0.9);
                font-size: 26rpx;
                text-shadow: 0 1rpx 4rpx rgba(0, 0, 0, 0.3);
              }
            }
          }
        }

        .filter-bar {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 20rpx 24rpx;
          border-bottom: 1rpx solid #f0f0f0;

          .filter-left {
            display: flex;
            gap: 16rpx;

            .filter-chip {
              display: flex;
              align-items: center;
              gap: 8rpx;
              padding: 12rpx 24rpx;
              background: #f8f9fa;
              border-radius: 32rpx;
              transition: all 0.3s ease;

              &:active {
                background: #e9ecef;
                transform: scale(0.98);
              }

              .chip-text {
                font-size: 26rpx;
                color: #666666;
              }

              .iconfont {
                font-size: 20rpx;
                color: #999999;
              }
            }
          }

          .view-switch {
            width: 56rpx;
            height: 56rpx;
            background: #f8f9fa;
            border-radius: 28rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;

            &:active {
              background: #e9ecef;
              transform: scale(0.95);
            }

            .iconfont {
              font-size: 28rpx;
              color: #667eea;
            }
          }
        }
      }

      .goods-section {
        padding: 16rpx;

        .skeleton-wrapper {
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          gap: 16rpx;

          .skeleton-item {
            background: #ffffff;
            border-radius: 16rpx;
            overflow: hidden;

            .skeleton-image {
              width: 100%;
              padding-bottom: 100%;
              background: linear-gradient(
                90deg,
                #f0f0f0 25%,
                #e0e0e0 50%,
                #f0f0f0 75%
              );
              background-size: 200% 100%;
              animation: loading 1.5s infinite;
            }

            .skeleton-text {
              height: 36rpx;
              background: #f0f0f0;
              margin: 16rpx;
              border-radius: 4rpx;
            }

            .skeleton-price {
              height: 28rpx;
              width: 50%;
              background: #f0f0f0;
              margin: 0 16rpx 16rpx;
              border-radius: 4rpx;
            }
          }
        }

        @keyframes loading {
          0% {
            background-position: 200% 0;
          }
          100% {
            background-position: -200% 0;
          }
        }

        .goods-grid {
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          gap: 16rpx;

          .goods-card {
            background: #ffffff;
            border-radius: 16rpx;
            overflow: hidden;
            transition: transform 0.3s ease, box-shadow 0.3s ease;

            &:active {
              transform: scale(0.98);
              box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
            }

            .card-inner {
              .image-wrapper {
                position: relative;
                width: 100%;
                padding-bottom: 100%;
                overflow: hidden;
                background: #f8f8f8;
                border-radius: 12rpx 12rpx 0 0;

                .goods-image {
                  position: absolute;
                  top: 0;
                  left: 0;
                  width: 100%;
                  height: 100%;
                  object-fit: cover;
                  display: block;
                }

                .promotion-tag {
                  position: absolute;
                  top: 12rpx;
                  left: 12rpx;
                  padding: 6rpx 16rpx;
                  background: linear-gradient(135deg, #ff6b6b 0%, #ff5252 100%);
                  color: #ffffff;
                  font-size: 22rpx;
                  font-weight: 500;
                  border-radius: 20rpx;
                  box-shadow: 0 2rpx 8rpx rgba(255, 82, 82, 0.3);
                }
              }

              .goods-info {
                padding: 16rpx;

                .goods-title {
                  font-size: 28rpx;
                  color: #333333;
                  line-height: 1.4;
                  display: -webkit-box;
                  -webkit-line-clamp: 2;
                  -webkit-box-orient: vertical;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  margin-bottom: 16rpx;
                }

                .price-section {
                  display: flex;
                  align-items: baseline;
                  gap: 8rpx;

                  .price-main {
                    display: flex;
                    align-items: baseline;

                    .price-symbol {
                      font-size: 22rpx;
                      color: #ff5252;
                      font-weight: 600;
                    }

                    .price-value {
                      font-size: 32rpx;
                      color: #ff5252;
                      font-weight: 700;
                      margin-left: 2rpx;
                    }
                  }

                  .price-original {
                    font-size: 24rpx;
                    color: #999999;
                    text-decoration: line-through;
                  }
                }
              }
            }
          }
        }

        .load-more-wrapper {
          padding: 40rpx 0 60rpx;
        }

        .empty-wrapper {
          padding: 100rpx 0;
        }
      }
    }
  }
}

.store-popup {
  background: #ffffff;
  border-radius: 24rpx 24rpx 0 0;
  max-height: 75vh;
  display: flex;
  flex-direction: column;

  .popup-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 32rpx;
    border-bottom: 1rpx solid #f0f0f0;

    .popup-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #2d3561;
    }

    .close-btn {
      width: 48rpx;
      height: 48rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #f8f9fa;
      border-radius: 50%;
      transition: all 0.3s ease;

      &:active {
        background: #e9ecef;
        transform: scale(0.95);
      }

      .iconfont {
        font-size: 28rpx;
        color: #666666;
      }
    }
  }

  .store-list {
    flex: 1;
    overflow-y: auto;
    padding: 16rpx;

    .store-item {
      display: flex;
      align-items: center;
      padding: 24rpx;
      margin-bottom: 16rpx;
      background: #f8f9fa;
      border-radius: 16rpx;
      transition: all 0.3s ease;

      &.active {
        background: linear-gradient(135deg, #f8f9ff 0%, #f3f5ff 100%);
        box-shadow: 0 2rpx 12rpx rgba(102, 126, 234, 0.08);
      }

      &:active {
        transform: scale(0.98);
      }

      .store-item-icon {
        width: 56rpx;
        height: 56rpx;
        background: #ffffff;
        border-radius: 12rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 20rpx;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);

        .iconfont {
          font-size: 28rpx;
          color: #667eea;
        }
      }

      .store-item-content {
        flex: 1;
        min-width: 0;

        .store-item-name {
          display: block;
          font-size: 30rpx;
          font-weight: 500;
          color: #2d3561;
          margin-bottom: 8rpx;
        }

        .store-item-address {
          display: block;
          font-size: 26rpx;
          color: #8892b0;
          line-height: 1.4;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
      }

      .store-item-extra {
        display: flex;
        align-items: center;
        gap: 16rpx;
        margin-left: 20rpx;

        .store-item-distance {
          font-size: 26rpx;
          color: #667eea;
          font-weight: 500;
        }

        .check-icon {
          width: 40rpx;
          height: 40rpx;
          background: #667eea;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;

          .iconfont {
            color: #ffffff;
            font-size: 20rpx;
          }
        }
      }
    }
  }

  .empty-state,
  .loading-state {
    padding: 100rpx 32rpx;
    text-align: center;

    .iconfont {
      font-size: 80rpx;
      color: #ddd;
      margin-bottom: 24rpx;
      display: block;
    }

    .empty-text,
    .loading-text {
      font-size: 28rpx;
      color: #999999;
    }
  }
}


</style>
